<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Support\Facades\Cache;
use App\Services\ApplyGoldCoinWithdrawXzbPay\AuthGoldCoinWithdrawXzbPay;
use App\Services\ApplyGoldCoinWithdrawXzbPay\AuthGoldCoinWithdrawXzbPayRequest;
use App\Services\ApplyGoldCoinWithdrawXzbPay\ApplyGoldCoinWithdrawXzbPay;
use App\Services\ApplyGoldCoinWithdrawXzbPay\ApplyGoldCoinWithdrawXzbPayRequest;



class WithdrawsXzbPayController extends Controller
{
	public function store()
    {
    	fail('银行卡提现暂未开通');
    	$lock = Cache::lock('withdraw', 1);
    	
    	try {
		    

    		if (! $lock->get()) fail('太快了，请再试一次');
		
    		$request = app(ApplyGoldCoinWithdrawXzbPayRequest::class);
    		
    		$user = $request->user();
    		
    		if (empty($request->pay_code)) {
    			fail('请输入交易密码');
		    }

		    $withdraw = $user->withdraws()->where('method','xzbpay')->orderByDesc('id')->first();
		    
		    if($withdraw){
		    	if($withdraw->status  == 'pending'){
		    		fail('您有审核中的提现记录，不可重复提交');
		    	}
		    }
		    
		    app(ApplyGoldCoinWithdrawXzbPay::class, [
			    'user' => $user,
			    'coins' => $request->coins,
			    'payCode' => $request->pay_code,
		    ])->apply();

		    $user->resetPayCodeTry();
		    
	    } finally {
    		$lock->release();
	    }
	    
	    return response(null, 204);
    }


	public function record()
	{

		$withdraw = request()->user()->withdraws()->where('method','sandpay')->orderByDesc('id')->first();
		if(!$withdraw){
			return response()->json(['code' => 200, 'msg'=> 'success', 'data' => null ]);
		}
		return response()->json(['code' => 200, 'msg'=> 'success', 'data' => $withdraw->toArray() ]);
	}

	public function auth()
	{
		/**
		 * Auth for freelance withdrawing.
		 */

		$request = app(AuthGoldCoinWithdrawXzbPayRequest::class);
		$user = request()->user();
		$res = app(AuthGoldCoinWithdrawXzbPay::class, ['user' => $user])->auth();

		return response()->json(['code' => 200, 'msg'=> 'success', 'data' => $res->toArray() ]);
	}
}
